{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a587ce4e",
   "metadata": {},
   "source": [
    "# Running Tune experiments with Optuna\n",
    "\n",
    "<a id=\"try-anyscale-quickstart-ray-tune-optuna_example\" href=\"https://console.anyscale.com/register/ha?render_flow=ray&utm_source=ray_docs&utm_medium=docs&utm_campaign=ray-tune-optuna_example\">\n",
    "    <img src=\"../../_static/img/run-on-anyscale.svg\" alt=\"try-anyscale-quickstart\">\n",
    "</a>\n",
    "<br></br>\n",
    "\n",
    "In this tutorial we introduce Optuna, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Optuna and, as a result, allow you to seamlessly scale up a Optuna optimization process - without sacrificing performance.\n",
    "\n",
    "Similar to Ray Tune, Optuna is an automatic hyperparameter optimization software framework, particularly designed for machine learning. It features an imperative (\"how\" over \"what\" emphasis), define-by-run style user API. With Optuna, a user has the ability to dynamically construct the search spaces for the hyperparameters. Optuna falls in the domain of \"derivative-free optimization\" and \"black-box optimization\".\n",
    "\n",
    "In this example we minimize a simple objective to briefly demonstrate the usage of Optuna with Ray Tune via `OptunaSearch`, including examples of conditional search spaces (string together relationships between hyperparameters), and the multi-objective problem (measure trade-offs among all important metrics). It's useful to keep in mind that despite the emphasis on machine learning experiments, Ray Tune optimizes any implicit or explicit objective. Here we assume `optuna>=3.0.0` library is installed. To learn more, please refer to [Optuna website](https://optuna.org/).\n",
    "\n",
    "Please note that sophisticated schedulers, such as `AsyncHyperBandScheduler`, may not work correctly with multi-objective optimization, since they typically expect a scalar score to compare fitness among trials.\n",
    "\n",
    "## Prerequisites"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aeaf9ff0",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "# !pip install \"ray[tune]\"\n",
    "!pip install -q \"optuna>=3.0.0\"\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "467466a3",
   "metadata": {},
   "source": [
    "Next, import the necessary libraries:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fb1ad624",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "import time\n",
    "from typing import Dict, Optional, Any\n",
    "\n",
    "import ray\n",
    "from ray import tune\n",
    "from ray.tune.search import ConcurrencyLimiter\n",
    "from ray.tune.search.optuna import OptunaSearch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e64f0b44",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b2da2a53d02f4c5b9a662b99548723f1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/html": [
       "<div class=\"lm-Widget p-Widget lm-Panel p-Panel jp-Cell-outputWrapper\">\n",
       "    <div style=\"margin-left: 50px;display: flex;flex-direction: row;align-items: center\">\n",
       "        <div class=\"jp-RenderedHTMLCommon\" style=\"display: flex; flex-direction: row;\">\n",
       "  <svg viewBox=\"0 0 567 224\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" style=\"height: 3em;\">\n",
       "    <g clip-path=\"url(#clip0_4338_178347)\">\n",
       "        <path d=\"M341.29 165.561H355.29L330.13 129.051C345.63 123.991 354.21 112.051 354.21 94.2307C354.21 71.3707 338.72 58.1807 311.88 58.1807H271V165.561H283.27V131.661H311.8C314.25 131.661 316.71 131.501 319.01 131.351L341.25 165.561H341.29ZM283.29 119.851V70.0007H311.82C331.3 70.0007 342.34 78.2907 342.34 94.5507C342.34 111.271 331.34 119.861 311.82 119.861L283.29 119.851ZM451.4 138.411L463.4 165.561H476.74L428.74 58.1807H416L367.83 165.561H380.83L392.83 138.411H451.4ZM446.19 126.601H398L422 72.1407L446.24 126.601H446.19ZM526.11 128.741L566.91 58.1807H554.35L519.99 114.181L485.17 58.1807H472.44L514.01 129.181V165.541H526.13V128.741H526.11Z\" fill=\"var(--jp-ui-font-color0)\"/>\n",
       "        <path d=\"M82.35 104.44C84.0187 97.8827 87.8248 92.0678 93.1671 87.9146C98.5094 83.7614 105.083 81.5067 111.85 81.5067C118.617 81.5067 125.191 83.7614 130.533 87.9146C135.875 92.0678 139.681 97.8827 141.35 104.44H163.75C164.476 101.562 165.622 98.8057 167.15 96.2605L127.45 56.5605C121.071 60.3522 113.526 61.6823 106.235 60.3005C98.9443 58.9187 92.4094 54.9203 87.8602 49.0574C83.3109 43.1946 81.0609 35.8714 81.5332 28.4656C82.0056 21.0599 85.1679 14.0819 90.4252 8.8446C95.6824 3.60726 102.672 0.471508 110.08 0.0272655C117.487 -0.416977 124.802 1.86091 130.647 6.4324C136.493 11.0039 140.467 17.5539 141.821 24.8501C143.175 32.1463 141.816 39.6859 138 46.0505L177.69 85.7505C182.31 82.9877 187.58 81.4995 192.962 81.4375C198.345 81.3755 203.648 82.742 208.33 85.3976C213.012 88.0532 216.907 91.9029 219.616 96.5544C222.326 101.206 223.753 106.492 223.753 111.875C223.753 117.258 222.326 122.545 219.616 127.197C216.907 131.848 213.012 135.698 208.33 138.353C203.648 141.009 198.345 142.375 192.962 142.313C187.58 142.251 182.31 140.763 177.69 138L138 177.7C141.808 184.071 143.155 191.614 141.79 198.91C140.424 206.205 136.44 212.75 130.585 217.313C124.731 221.875 117.412 224.141 110.004 223.683C102.596 223.226 95.6103 220.077 90.3621 214.828C85.1139 209.58 81.9647 202.595 81.5072 195.187C81.0497 187.779 83.3154 180.459 87.878 174.605C92.4405 168.751 98.9853 164.766 106.281 163.401C113.576 162.035 121.119 163.383 127.49 167.19L167.19 127.49C165.664 124.941 164.518 122.182 163.79 119.3H141.39C139.721 125.858 135.915 131.673 130.573 135.826C125.231 139.98 118.657 142.234 111.89 142.234C105.123 142.234 98.5494 139.98 93.2071 135.826C87.8648 131.673 84.0587 125.858 82.39 119.3H60C58.1878 126.495 53.8086 132.78 47.6863 136.971C41.5641 141.163 34.1211 142.972 26.7579 142.059C19.3947 141.146 12.6191 137.574 7.70605 132.014C2.79302 126.454 0.0813599 119.29 0.0813599 111.87C0.0813599 104.451 2.79302 97.2871 7.70605 91.7272C12.6191 86.1673 19.3947 82.5947 26.7579 81.6817C34.1211 80.7686 41.5641 82.5781 47.6863 86.7696C53.8086 90.9611 58.1878 97.2456 60 104.44H82.35ZM100.86 204.32C103.407 206.868 106.759 208.453 110.345 208.806C113.93 209.159 117.527 208.258 120.522 206.256C123.517 204.254 125.725 201.276 126.771 197.828C127.816 194.38 127.633 190.677 126.253 187.349C124.874 184.021 122.383 181.274 119.205 179.577C116.027 177.88 112.359 177.337 108.826 178.042C105.293 178.746 102.113 180.654 99.8291 183.44C97.5451 186.226 96.2979 189.718 96.3 193.32C96.2985 195.364 96.7006 197.388 97.4831 199.275C98.2656 201.163 99.4132 202.877 100.86 204.32ZM204.32 122.88C206.868 120.333 208.453 116.981 208.806 113.396C209.159 109.811 208.258 106.214 206.256 103.219C204.254 100.223 201.275 98.0151 197.827 96.97C194.38 95.9249 190.676 96.1077 187.348 97.4873C184.02 98.8669 181.274 101.358 179.577 104.536C177.879 107.714 177.337 111.382 178.041 114.915C178.746 118.448 180.653 121.627 183.439 123.911C186.226 126.195 189.717 127.443 193.32 127.44C195.364 127.443 197.388 127.042 199.275 126.259C201.163 125.476 202.878 124.328 204.32 122.88ZM122.88 19.4205C120.333 16.8729 116.981 15.2876 113.395 14.9347C109.81 14.5817 106.213 15.483 103.218 17.4849C100.223 19.4868 98.0146 22.4654 96.9696 25.9131C95.9245 29.3608 96.1073 33.0642 97.4869 36.3922C98.8665 39.7202 101.358 42.4668 104.535 44.1639C107.713 45.861 111.381 46.4036 114.914 45.6992C118.447 44.9949 121.627 43.0871 123.911 40.301C126.195 37.515 127.442 34.0231 127.44 30.4205C127.44 28.3772 127.038 26.3539 126.255 24.4664C125.473 22.5788 124.326 20.8642 122.88 19.4205ZM19.42 100.86C16.8725 103.408 15.2872 106.76 14.9342 110.345C14.5813 113.93 15.4826 117.527 17.4844 120.522C19.4863 123.518 22.4649 125.726 25.9127 126.771C29.3604 127.816 33.0638 127.633 36.3918 126.254C39.7198 124.874 42.4664 122.383 44.1635 119.205C45.8606 116.027 46.4032 112.359 45.6988 108.826C44.9944 105.293 43.0866 102.114 40.3006 99.8296C37.5145 97.5455 34.0227 96.2983 30.42 96.3005C26.2938 96.3018 22.337 97.9421 19.42 100.86ZM100.86 100.86C98.3125 103.408 96.7272 106.76 96.3742 110.345C96.0213 113.93 96.9226 117.527 98.9244 120.522C100.926 123.518 103.905 125.726 107.353 126.771C110.8 127.816 114.504 127.633 117.832 126.254C121.16 124.874 123.906 122.383 125.604 119.205C127.301 116.027 127.843 112.359 127.139 108.826C126.434 105.293 124.527 102.114 121.741 99.8296C118.955 97.5455 115.463 96.2983 111.86 96.3005C109.817 96.299 107.793 96.701 105.905 97.4835C104.018 98.2661 102.303 99.4136 100.86 100.86Z\" fill=\"#00AEEF\"/>\n",
       "    </g>\n",
       "    <defs>\n",
       "        <clipPath id=\"clip0_4338_178347\">\n",
       "            <rect width=\"566.93\" height=\"223.75\" fill=\"white\"/>\n",
       "        </clipPath>\n",
       "    </defs>\n",
       "  </svg>\n",
       "</div>\n",
       "\n",
       "        <table class=\"jp-RenderedHTMLCommon\" style=\"border-collapse: collapse;color: var(--jp-ui-font-color1);font-size: var(--jp-ui-font-size1);\">\n",
       "    <tr>\n",
       "        <td style=\"text-align: left\"><b>Python version:</b></td>\n",
       "        <td style=\"text-align: left\"><b>3.10.16</b></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <td style=\"text-align: left\"><b>Ray version:</b></td>\n",
       "        <td style=\"text-align: left\"><b>2.42.0</b></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "    <td style=\"text-align: left\"><b>Dashboard:</b></td>\n",
       "    <td style=\"text-align: left\"><b><a href=\"http://127.0.0.1:8265\" target=\"_blank\">http://127.0.0.1:8265</a></b></td>\n",
       "</tr>\n",
       "\n",
       "</table>\n",
       "\n",
       "    </div>\n",
       "</div>\n"
      ],
      "text/plain": [
       "RayContext(dashboard_url='127.0.0.1:8265', python_version='3.10.16', ray_version='2.42.0', ray_commit='637116a090c052d061af5ba3bef8a467c8c3fc25')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ray.init(configure_logging=False)  # initialize Ray"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "56b0c685",
   "metadata": {},
   "source": [
    "Let's start by defining a simple evaluation function.\n",
    "An explicit math formula is queried here for demonstration, yet in practice this is typically a black-box function-- e.g. the performance results after training an ML model.\n",
    "We artificially sleep for a bit (`0.1` seconds) to simulate a long-running ML experiment.\n",
    "This setup assumes that we're running multiple `step`s of an experiment while tuning three hyperparameters,\n",
    "namely `width`, `height`, and `activation`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "90a11f98",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(step, width, height, activation):\n",
    "    time.sleep(0.1)\n",
    "    activation_boost = 10 if activation==\"relu\" else 0\n",
    "    return (0.1 + width * step / 100) ** (-1) + height * 0.1 + activation_boost"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bc579b83",
   "metadata": {},
   "source": [
    "Next, our `objective` function to be optimized takes a Tune `config`, evaluates the `score` of your experiment in a training loop,\n",
    "and uses `tune.report` to report the `score` back to Tune."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "3a11d0e0",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "def objective(config):\n",
    "    for step in range(config[\"steps\"]):\n",
    "        score = evaluate(step, config[\"width\"], config[\"height\"], config[\"activation\"])\n",
    "        tune.report({\"iterations\": step, \"mean_loss\": score})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c58bd20b",
   "metadata": {},
   "source": [
    "Next we define a search space. The critical assumption is that the optimal hyperparameters live within this space. Yet, if the space is very large, then those hyperparameters may be difficult to find in a short amount of time.\n",
    "\n",
    "The simplest case is a search space with independent dimensions. In this case, a config dictionary will suffice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c3e4eecb",
   "metadata": {},
   "outputs": [],
   "source": [
    "search_space = {\n",
    "    \"steps\": 100,\n",
    "    \"width\": tune.uniform(0, 20),\n",
    "    \"height\": tune.uniform(-100, 100),\n",
    "    \"activation\": tune.choice([\"relu\", \"tanh\"]),\n",
    "}"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ef0c666d",
   "metadata": {},
   "source": [
    "Here we define the Optuna search algorithm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f23cadc8",
   "metadata": {},
   "outputs": [],
   "source": [
    "algo = OptunaSearch()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4287fa79",
   "metadata": {},
   "source": [
    "We also constrain the number of concurrent trials to `4` with a `ConcurrencyLimiter`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "68022ea4",
   "metadata": {},
   "outputs": [],
   "source": [
    "algo = ConcurrencyLimiter(algo, max_concurrent=4)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4c250f74",
   "metadata": {},
   "source": [
    "The number of samples is the number of hyperparameter combinations that will be tried out. This Tune run is set to `1000` samples.\n",
    "(you can decrease this if it takes too long on your machine)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f6c21314",
   "metadata": {},
   "outputs": [],
   "source": [
    "num_samples = 1000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9533aabf",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# We override here for our smoke tests.\n",
    "num_samples = 10"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "92942b88",
   "metadata": {},
   "source": [
    "Finally, we run the experiment to `\"min\"`imize the \"mean_loss\" of the `objective` by searching `search_space` via `algo`, `num_samples` times. This previous sentence is fully characterizes the search problem we aim to solve. With this in mind, notice how efficient it is to execute `tuner.fit()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4e224bb2",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"tuneStatus\">\n",
       "  <div style=\"display: flex;flex-direction: row\">\n",
       "    <div style=\"display: flex;flex-direction: column;\">\n",
       "      <h3>Tune Status</h3>\n",
       "      <table>\n",
       "<tbody>\n",
       "<tr><td>Current time:</td><td>2025-02-10 18:06:12</td></tr>\n",
       "<tr><td>Running for: </td><td>00:00:35.68        </td></tr>\n",
       "<tr><td>Memory:      </td><td>22.7/36.0 GiB      </td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "    </div>\n",
       "    <div class=\"vDivider\"></div>\n",
       "    <div class=\"systemInfo\">\n",
       "      <h3>System Info</h3>\n",
       "      Using FIFO scheduling algorithm.<br>Logical resource usage: 1.0/12 CPUs, 0/0 GPUs\n",
       "    </div>\n",
       "    \n",
       "  </div>\n",
       "  <div class=\"hDivider\"></div>\n",
       "  <div class=\"trialStatus\">\n",
       "    <h3>Trial Status</h3>\n",
       "    <table>\n",
       "<thead>\n",
       "<tr><th>Trial name        </th><th>status    </th><th>loc            </th><th>activation  </th><th style=\"text-align: right;\">   height</th><th style=\"text-align: right;\">   width</th><th style=\"text-align: right;\">    loss</th><th style=\"text-align: right;\">  iter</th><th style=\"text-align: right;\">  total time (s)</th><th style=\"text-align: right;\">  iterations</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "<tr><td>objective_989a402c</td><td>TERMINATED</td><td>127.0.0.1:42307</td><td>relu        </td><td style=\"text-align: right;\">  6.57558</td><td style=\"text-align: right;\"> 8.66313</td><td style=\"text-align: right;\">10.7728 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3642</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_d99d28c6</td><td>TERMINATED</td><td>127.0.0.1:42321</td><td>tanh        </td><td style=\"text-align: right;\"> 51.2103 </td><td style=\"text-align: right;\">19.2804 </td><td style=\"text-align: right;\"> 5.17314</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3775</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_ce34b92b</td><td>TERMINATED</td><td>127.0.0.1:42323</td><td>tanh        </td><td style=\"text-align: right;\">-49.4554 </td><td style=\"text-align: right;\">17.2683 </td><td style=\"text-align: right;\">-4.88739</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3741</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_f650ea5f</td><td>TERMINATED</td><td>127.0.0.1:42332</td><td>tanh        </td><td style=\"text-align: right;\"> 20.6147 </td><td style=\"text-align: right;\"> 3.19539</td><td style=\"text-align: right;\"> 2.3679 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3804</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_e72e976e</td><td>TERMINATED</td><td>127.0.0.1:42356</td><td>relu        </td><td style=\"text-align: right;\">-12.5302 </td><td style=\"text-align: right;\"> 3.45152</td><td style=\"text-align: right;\"> 9.03132</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.372 </td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_d00b4e1a</td><td>TERMINATED</td><td>127.0.0.1:42362</td><td>tanh        </td><td style=\"text-align: right;\"> 65.8592 </td><td style=\"text-align: right;\"> 3.14335</td><td style=\"text-align: right;\"> 6.89726</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3776</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_30c6ec86</td><td>TERMINATED</td><td>127.0.0.1:42367</td><td>tanh        </td><td style=\"text-align: right;\">-82.0713 </td><td style=\"text-align: right;\">14.2595 </td><td style=\"text-align: right;\">-8.13679</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3755</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_691ce63c</td><td>TERMINATED</td><td>127.0.0.1:42368</td><td>tanh        </td><td style=\"text-align: right;\"> 29.406  </td><td style=\"text-align: right;\"> 2.21881</td><td style=\"text-align: right;\"> 3.37602</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3653</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_3051162c</td><td>TERMINATED</td><td>127.0.0.1:42404</td><td>relu        </td><td style=\"text-align: right;\"> 61.1787 </td><td style=\"text-align: right;\">12.9673 </td><td style=\"text-align: right;\">16.1952 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3885</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_04a38992</td><td>TERMINATED</td><td>127.0.0.1:42405</td><td>relu        </td><td style=\"text-align: right;\">  6.28688</td><td style=\"text-align: right;\">11.4537 </td><td style=\"text-align: right;\">10.7161 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.4051</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "  </div>\n",
       "</div>\n",
       "<style>\n",
       ".tuneStatus {\n",
       "  color: var(--jp-ui-font-color1);\n",
       "}\n",
       ".tuneStatus .systemInfo {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus td {\n",
       "  white-space: nowrap;\n",
       "}\n",
       ".tuneStatus .trialStatus {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus h3 {\n",
       "  font-weight: bold;\n",
       "}\n",
       ".tuneStatus .hDivider {\n",
       "  border-bottom-width: var(--jp-border-width);\n",
       "  border-bottom-color: var(--jp-border-color0);\n",
       "  border-bottom-style: solid;\n",
       "}\n",
       ".tuneStatus .vDivider {\n",
       "  border-left-width: var(--jp-border-width);\n",
       "  border-left-color: var(--jp-border-color0);\n",
       "  border-left-style: solid;\n",
       "  margin: 0.5em 1em 0.5em 1em;\n",
       "}\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tuner = tune.Tuner(\n",
    "    objective,\n",
    "    tune_config=tune.TuneConfig(\n",
    "        metric=\"mean_loss\",\n",
    "        mode=\"min\",\n",
    "        search_alg=algo,\n",
    "        num_samples=num_samples,\n",
    "    ),\n",
    "    param_space=search_space,\n",
    ")\n",
    "results = tuner.fit()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b66aab6a",
   "metadata": {},
   "source": [
    "And now we have the hyperparameters found to minimize the mean loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e69db02e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best hyperparameters found were:  {'steps': 100, 'width': 14.259467682064852, 'height': -82.07132174642958, 'activation': 'tanh'}\n"
     ]
    }
   ],
   "source": [
    "print(\"Best hyperparameters found were: \", results.get_best_result().config)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d545d30b",
   "metadata": {},
   "source": [
    "## Providing an initial set of hyperparameters\n",
    "\n",
    "While defining the search algorithm, we may choose to provide an initial set of hyperparameters that we believe are especially promising or informative, and\n",
    "pass this information as a helpful starting point for the `OptunaSearch` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7596b7f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "initial_params = [\n",
    "    {\"width\": 1, \"height\": 2, \"activation\": \"relu\"},\n",
    "    {\"width\": 4, \"height\": 2, \"activation\": \"relu\"},\n",
    "]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f84bbff0",
   "metadata": {},
   "source": [
    "Now the `search_alg` built using `OptunaSearch` takes `points_to_evaluate`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "320d1935",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "searcher = OptunaSearch(points_to_evaluate=initial_params)\n",
    "algo = ConcurrencyLimiter(searcher, max_concurrent=4)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9147d9a2",
   "metadata": {},
   "source": [
    "And run the experiment with initial hyperparameter evaluations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ee442efd",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"tuneStatus\">\n",
       "  <div style=\"display: flex;flex-direction: row\">\n",
       "    <div style=\"display: flex;flex-direction: column;\">\n",
       "      <h3>Tune Status</h3>\n",
       "      <table>\n",
       "<tbody>\n",
       "<tr><td>Current time:</td><td>2025-02-10 18:06:47</td></tr>\n",
       "<tr><td>Running for: </td><td>00:00:35.44        </td></tr>\n",
       "<tr><td>Memory:      </td><td>22.7/36.0 GiB      </td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "    </div>\n",
       "    <div class=\"vDivider\"></div>\n",
       "    <div class=\"systemInfo\">\n",
       "      <h3>System Info</h3>\n",
       "      Using FIFO scheduling algorithm.<br>Logical resource usage: 1.0/12 CPUs, 0/0 GPUs\n",
       "    </div>\n",
       "    \n",
       "  </div>\n",
       "  <div class=\"hDivider\"></div>\n",
       "  <div class=\"trialStatus\">\n",
       "    <h3>Trial Status</h3>\n",
       "    <table>\n",
       "<thead>\n",
       "<tr><th>Trial name        </th><th>status    </th><th>loc            </th><th>activation  </th><th style=\"text-align: right;\">   height</th><th style=\"text-align: right;\">   width</th><th style=\"text-align: right;\">     loss</th><th style=\"text-align: right;\">  iter</th><th style=\"text-align: right;\">  total time (s)</th><th style=\"text-align: right;\">  iterations</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "<tr><td>objective_1d2e715f</td><td>TERMINATED</td><td>127.0.0.1:42435</td><td>relu        </td><td style=\"text-align: right;\">  2      </td><td style=\"text-align: right;\"> 1      </td><td style=\"text-align: right;\">11.1174  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3556</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_f7c2aed0</td><td>TERMINATED</td><td>127.0.0.1:42436</td><td>relu        </td><td style=\"text-align: right;\">  2      </td><td style=\"text-align: right;\"> 4      </td><td style=\"text-align: right;\">10.4463  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3702</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_09dcce33</td><td>TERMINATED</td><td>127.0.0.1:42438</td><td>tanh        </td><td style=\"text-align: right;\"> 28.5547 </td><td style=\"text-align: right;\">17.4195 </td><td style=\"text-align: right;\"> 2.91312 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3483</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_b9955517</td><td>TERMINATED</td><td>127.0.0.1:42443</td><td>tanh        </td><td style=\"text-align: right;\">-73.0995 </td><td style=\"text-align: right;\">13.8859 </td><td style=\"text-align: right;\">-7.23773 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3682</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_d81ebd5c</td><td>TERMINATED</td><td>127.0.0.1:42464</td><td>relu        </td><td style=\"text-align: right;\"> -1.86597</td><td style=\"text-align: right;\"> 1.46093</td><td style=\"text-align: right;\">10.4601  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3969</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_3f0030e7</td><td>TERMINATED</td><td>127.0.0.1:42465</td><td>relu        </td><td style=\"text-align: right;\"> 38.7166 </td><td style=\"text-align: right;\"> 1.3696 </td><td style=\"text-align: right;\">14.5585  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3741</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_86bf6402</td><td>TERMINATED</td><td>127.0.0.1:42470</td><td>tanh        </td><td style=\"text-align: right;\"> 40.269  </td><td style=\"text-align: right;\"> 5.13015</td><td style=\"text-align: right;\"> 4.21999 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3769</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_75d06a83</td><td>TERMINATED</td><td>127.0.0.1:42471</td><td>tanh        </td><td style=\"text-align: right;\">-11.2824 </td><td style=\"text-align: right;\"> 3.10251</td><td style=\"text-align: right;\">-0.812933</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3695</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_0d197811</td><td>TERMINATED</td><td>127.0.0.1:42496</td><td>tanh        </td><td style=\"text-align: right;\"> 91.7076 </td><td style=\"text-align: right;\">15.1032 </td><td style=\"text-align: right;\"> 9.2372  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3631</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_5156451f</td><td>TERMINATED</td><td>127.0.0.1:42497</td><td>tanh        </td><td style=\"text-align: right;\"> 58.9282 </td><td style=\"text-align: right;\"> 3.96315</td><td style=\"text-align: right;\"> 6.14136 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.4732</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "  </div>\n",
       "</div>\n",
       "<style>\n",
       ".tuneStatus {\n",
       "  color: var(--jp-ui-font-color1);\n",
       "}\n",
       ".tuneStatus .systemInfo {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus td {\n",
       "  white-space: nowrap;\n",
       "}\n",
       ".tuneStatus .trialStatus {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus h3 {\n",
       "  font-weight: bold;\n",
       "}\n",
       ".tuneStatus .hDivider {\n",
       "  border-bottom-width: var(--jp-border-width);\n",
       "  border-bottom-color: var(--jp-border-color0);\n",
       "  border-bottom-style: solid;\n",
       "}\n",
       ".tuneStatus .vDivider {\n",
       "  border-left-width: var(--jp-border-width);\n",
       "  border-left-color: var(--jp-border-color0);\n",
       "  border-left-style: solid;\n",
       "  margin: 0.5em 1em 0.5em 1em;\n",
       "}\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tuner = tune.Tuner(\n",
    "    objective,\n",
    "    tune_config=tune.TuneConfig(\n",
    "        metric=\"mean_loss\",\n",
    "        mode=\"min\",\n",
    "        search_alg=algo,\n",
    "        num_samples=num_samples,\n",
    "    ),\n",
    "    param_space=search_space,\n",
    ")\n",
    "results = tuner.fit()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ccfe15e2",
   "metadata": {},
   "source": [
    "We take another look at the optimal hyperparameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "fcfa0c2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best hyperparameters found were:  {'steps': 100, 'width': 13.885889617119432, 'height': -73.09947583621019, 'activation': 'tanh'}\n"
     ]
    }
   ],
   "source": [
    "print(\"Best hyperparameters found were: \", results.get_best_result().config)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "88080576",
   "metadata": {},
   "source": [
    "## Conditional search spaces \n",
    "\n",
    "Sometimes we may want to build a more complicated search space that has conditional dependencies on other hyperparameters. In this case, we pass a define-by-run function to the `search_alg` argument in `ray.tune()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f0acc2fc",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "def define_by_run_func(trial) -> Optional[Dict[str, Any]]:\n",
    "    \"\"\"Define-by-run function to construct a conditional search space.\n",
    "\n",
    "    Ensure no actual computation takes place here. That should go into\n",
    "    the trainable passed to ``Tuner()`` (in this example, that's\n",
    "    ``objective``).\n",
    "\n",
    "    For more information, see https://optuna.readthedocs.io/en/stable\\\n",
    "    /tutorial/10_key_features/002_configurations.html\n",
    "\n",
    "    Args:\n",
    "        trial: Optuna Trial object\n",
    "        \n",
    "    Returns:\n",
    "        Dict containing constant parameters or None\n",
    "    \"\"\"\n",
    "\n",
    "    activation = trial.suggest_categorical(\"activation\", [\"relu\", \"tanh\"])\n",
    "\n",
    "    # Define-by-run allows for conditional search spaces.\n",
    "    if activation == \"relu\":\n",
    "        trial.suggest_float(\"width\", 0, 20)\n",
    "        trial.suggest_float(\"height\", -100, 100)\n",
    "    else:\n",
    "        trial.suggest_float(\"width\", -1, 21)\n",
    "        trial.suggest_float(\"height\", -101, 101)\n",
    "        \n",
    "    # Return all constants in a dictionary.\n",
    "    return {\"steps\": 100}"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4c9d0945",
   "metadata": {},
   "source": [
    "As before, we create the `search_alg` from `OptunaSearch` and `ConcurrencyLimiter`, this time we define the scope of search via the `space` argument and provide no initialization. We also must specific metric and mode when using `space`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "906f9ffc",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2025-02-10 18:06:47,670] A new study created in memory with name: optuna\n"
     ]
    }
   ],
   "source": [
    "searcher = OptunaSearch(space=define_by_run_func, metric=\"mean_loss\", mode=\"min\")\n",
    "algo = ConcurrencyLimiter(searcher, max_concurrent=4)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "fea9399c",
   "metadata": {},
   "source": [
    "Running the experiment with a define-by-run search space:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "bf0ee932",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"tuneStatus\">\n",
       "  <div style=\"display: flex;flex-direction: row\">\n",
       "    <div style=\"display: flex;flex-direction: column;\">\n",
       "      <h3>Tune Status</h3>\n",
       "      <table>\n",
       "<tbody>\n",
       "<tr><td>Current time:</td><td>2025-02-10 18:07:23</td></tr>\n",
       "<tr><td>Running for: </td><td>00:00:35.58        </td></tr>\n",
       "<tr><td>Memory:      </td><td>22.9/36.0 GiB      </td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "    </div>\n",
       "    <div class=\"vDivider\"></div>\n",
       "    <div class=\"systemInfo\">\n",
       "      <h3>System Info</h3>\n",
       "      Using FIFO scheduling algorithm.<br>Logical resource usage: 1.0/12 CPUs, 0/0 GPUs\n",
       "    </div>\n",
       "    \n",
       "  </div>\n",
       "  <div class=\"hDivider\"></div>\n",
       "  <div class=\"trialStatus\">\n",
       "    <h3>Trial Status</h3>\n",
       "    <table>\n",
       "<thead>\n",
       "<tr><th>Trial name        </th><th>status    </th><th>loc            </th><th>activation  </th><th style=\"text-align: right;\">   height</th><th style=\"text-align: right;\">  steps</th><th style=\"text-align: right;\">    width</th><th style=\"text-align: right;\">    loss</th><th style=\"text-align: right;\">  iter</th><th style=\"text-align: right;\">  total time (s)</th><th style=\"text-align: right;\">  iterations</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "<tr><td>objective_48aa8fed</td><td>TERMINATED</td><td>127.0.0.1:42529</td><td>relu        </td><td style=\"text-align: right;\">-76.595  </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\"> 9.90896 </td><td style=\"text-align: right;\"> 2.44141</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3957</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_5f395194</td><td>TERMINATED</td><td>127.0.0.1:42531</td><td>relu        </td><td style=\"text-align: right;\">-34.1447 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">12.9999  </td><td style=\"text-align: right;\"> 6.66263</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3823</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_e64a7441</td><td>TERMINATED</td><td>127.0.0.1:42532</td><td>relu        </td><td style=\"text-align: right;\">-50.3172 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\"> 3.95399 </td><td style=\"text-align: right;\"> 5.21738</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3839</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_8e668790</td><td>TERMINATED</td><td>127.0.0.1:42537</td><td>tanh        </td><td style=\"text-align: right;\"> 30.9768 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">16.22    </td><td style=\"text-align: right;\"> 3.15957</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3818</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_78ca576b</td><td>TERMINATED</td><td>127.0.0.1:42559</td><td>relu        </td><td style=\"text-align: right;\"> 80.5037 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\"> 0.906139</td><td style=\"text-align: right;\">19.0533 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3731</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_4cd9e37a</td><td>TERMINATED</td><td>127.0.0.1:42560</td><td>relu        </td><td style=\"text-align: right;\"> 77.0988 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\"> 8.43807 </td><td style=\"text-align: right;\">17.8282 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3881</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_a40498d5</td><td>TERMINATED</td><td>127.0.0.1:42565</td><td>tanh        </td><td style=\"text-align: right;\">-24.0393 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">12.7274  </td><td style=\"text-align: right;\">-2.32519</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.4031</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_43e7ea7e</td><td>TERMINATED</td><td>127.0.0.1:42566</td><td>tanh        </td><td style=\"text-align: right;\">-92.349  </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">15.8595  </td><td style=\"text-align: right;\">-9.17161</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.4602</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_cb92227e</td><td>TERMINATED</td><td>127.0.0.1:42591</td><td>relu        </td><td style=\"text-align: right;\">  3.58988</td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">17.3259  </td><td style=\"text-align: right;\">10.417  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3817</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "<tr><td>objective_abed5125</td><td>TERMINATED</td><td>127.0.0.1:42608</td><td>tanh        </td><td style=\"text-align: right;\"> 86.0127 </td><td style=\"text-align: right;\">    100</td><td style=\"text-align: right;\">11.2746  </td><td style=\"text-align: right;\"> 8.69007</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3995</td><td style=\"text-align: right;\">          99</td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "  </div>\n",
       "</div>\n",
       "<style>\n",
       ".tuneStatus {\n",
       "  color: var(--jp-ui-font-color1);\n",
       "}\n",
       ".tuneStatus .systemInfo {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus td {\n",
       "  white-space: nowrap;\n",
       "}\n",
       ".tuneStatus .trialStatus {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus h3 {\n",
       "  font-weight: bold;\n",
       "}\n",
       ".tuneStatus .hDivider {\n",
       "  border-bottom-width: var(--jp-border-width);\n",
       "  border-bottom-color: var(--jp-border-color0);\n",
       "  border-bottom-style: solid;\n",
       "}\n",
       ".tuneStatus .vDivider {\n",
       "  border-left-width: var(--jp-border-width);\n",
       "  border-left-color: var(--jp-border-color0);\n",
       "  border-left-style: solid;\n",
       "  margin: 0.5em 1em 0.5em 1em;\n",
       "}\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tuner = tune.Tuner(\n",
    "    objective,\n",
    "    tune_config=tune.TuneConfig(\n",
    "        search_alg=algo,\n",
    "        num_samples=num_samples,\n",
    "    ),\n",
    ")\n",
    "results = tuner.fit()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "11e1ee04",
   "metadata": {},
   "source": [
    "We take a look again at the optimal hyperparameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "13e4ce18",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best hyperparameters for loss found were:  {'activation': 'tanh', 'width': 15.859495323836288, 'height': -92.34898015005697, 'steps': 100}\n"
     ]
    }
   ],
   "source": [
    "print(\"Best hyperparameters for loss found were: \", results.get_best_result(\"mean_loss\", \"min\").config)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "34bbd066",
   "metadata": {},
   "source": [
    "## Multi-objective optimization\n",
    "\n",
    "Finally, let's take a look at the multi-objective case. This permits us to optimize multiple metrics at once, and organize our results based on the different objectives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "b233cbea",
   "metadata": {},
   "outputs": [],
   "source": [
    "def multi_objective(config):\n",
    "    # Hyperparameters\n",
    "    width, height = config[\"width\"], config[\"height\"]\n",
    "\n",
    "    for step in range(config[\"steps\"]):\n",
    "        # Iterative training function - can be any arbitrary training procedure\n",
    "        intermediate_score = evaluate(step, config[\"width\"], config[\"height\"], config[\"activation\"])\n",
    "        # Feed the score back back to Tune.\n",
    "        tune.report({\n",
    "           \"iterations\": step, \"loss\": intermediate_score, \"gain\": intermediate_score * width\n",
    "        })"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "338e5108",
   "metadata": {},
   "source": [
    "We define the `OptunaSearch` object this time with metric and mode as list arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "624d0bc8",
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"tuneStatus\">\n",
       "  <div style=\"display: flex;flex-direction: row\">\n",
       "    <div style=\"display: flex;flex-direction: column;\">\n",
       "      <h3>Tune Status</h3>\n",
       "      <table>\n",
       "<tbody>\n",
       "<tr><td>Current time:</td><td>2025-02-10 18:07:58</td></tr>\n",
       "<tr><td>Running for: </td><td>00:00:35.27        </td></tr>\n",
       "<tr><td>Memory:      </td><td>22.7/36.0 GiB      </td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "    </div>\n",
       "    <div class=\"vDivider\"></div>\n",
       "    <div class=\"systemInfo\">\n",
       "      <h3>System Info</h3>\n",
       "      Using FIFO scheduling algorithm.<br>Logical resource usage: 1.0/12 CPUs, 0/0 GPUs\n",
       "    </div>\n",
       "    \n",
       "  </div>\n",
       "  <div class=\"hDivider\"></div>\n",
       "  <div class=\"trialStatus\">\n",
       "    <h3>Trial Status</h3>\n",
       "    <table>\n",
       "<thead>\n",
       "<tr><th>Trial name              </th><th>status    </th><th>loc            </th><th>activation  </th><th style=\"text-align: right;\">  height</th><th style=\"text-align: right;\">   width</th><th style=\"text-align: right;\">  iter</th><th style=\"text-align: right;\">  total time (s)</th><th style=\"text-align: right;\">  iterations</th><th style=\"text-align: right;\">    loss</th><th style=\"text-align: right;\">     gain</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "<tr><td>multi_objective_0534ec01</td><td>TERMINATED</td><td>127.0.0.1:42659</td><td>tanh        </td><td style=\"text-align: right;\"> 18.3209</td><td style=\"text-align: right;\"> 8.1091 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3653</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 1.95513</td><td style=\"text-align: right;\"> 15.8543 </td></tr>\n",
       "<tr><td>multi_objective_d3a487a7</td><td>TERMINATED</td><td>127.0.0.1:42660</td><td>relu        </td><td style=\"text-align: right;\">-67.8896</td><td style=\"text-align: right;\"> 2.58816</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3682</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 3.58666</td><td style=\"text-align: right;\">  9.28286</td></tr>\n",
       "<tr><td>multi_objective_f481c3db</td><td>TERMINATED</td><td>127.0.0.1:42665</td><td>relu        </td><td style=\"text-align: right;\"> 46.6439</td><td style=\"text-align: right;\">19.5326 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3677</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\">14.7158 </td><td style=\"text-align: right;\">287.438  </td></tr>\n",
       "<tr><td>multi_objective_74a41d72</td><td>TERMINATED</td><td>127.0.0.1:42666</td><td>tanh        </td><td style=\"text-align: right;\">-31.9508</td><td style=\"text-align: right;\">11.413  </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3685</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\">-3.10735</td><td style=\"text-align: right;\">-35.4643 </td></tr>\n",
       "<tr><td>multi_objective_d673b1ae</td><td>TERMINATED</td><td>127.0.0.1:42695</td><td>relu        </td><td style=\"text-align: right;\"> 83.6004</td><td style=\"text-align: right;\"> 5.04972</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3494</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\">18.5561 </td><td style=\"text-align: right;\"> 93.7034 </td></tr>\n",
       "<tr><td>multi_objective_25ddc340</td><td>TERMINATED</td><td>127.0.0.1:42701</td><td>relu        </td><td style=\"text-align: right;\">-81.7161</td><td style=\"text-align: right;\"> 4.45303</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.382 </td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 2.05019</td><td style=\"text-align: right;\">  9.12955</td></tr>\n",
       "<tr><td>multi_objective_f8554c17</td><td>TERMINATED</td><td>127.0.0.1:42702</td><td>tanh        </td><td style=\"text-align: right;\"> 43.5854</td><td style=\"text-align: right;\"> 6.84585</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3638</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 4.50394</td><td style=\"text-align: right;\"> 30.8333 </td></tr>\n",
       "<tr><td>multi_objective_a144e315</td><td>TERMINATED</td><td>127.0.0.1:42707</td><td>tanh        </td><td style=\"text-align: right;\"> 39.8075</td><td style=\"text-align: right;\">19.1985 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3706</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 4.03309</td><td style=\"text-align: right;\"> 77.4292 </td></tr>\n",
       "<tr><td>multi_objective_50540842</td><td>TERMINATED</td><td>127.0.0.1:42739</td><td>relu        </td><td style=\"text-align: right;\"> 75.2805</td><td style=\"text-align: right;\">11.4041 </td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3529</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\">17.6158 </td><td style=\"text-align: right;\">200.893  </td></tr>\n",
       "<tr><td>multi_objective_f322a9e3</td><td>TERMINATED</td><td>127.0.0.1:42740</td><td>relu        </td><td style=\"text-align: right;\">-51.3587</td><td style=\"text-align: right;\"> 5.31683</td><td style=\"text-align: right;\">   100</td><td style=\"text-align: right;\">         10.3756</td><td style=\"text-align: right;\">          99</td><td style=\"text-align: right;\"> 5.05057</td><td style=\"text-align: right;\"> 26.853  </td></tr>\n",
       "</tbody>\n",
       "</table>\n",
       "  </div>\n",
       "</div>\n",
       "<style>\n",
       ".tuneStatus {\n",
       "  color: var(--jp-ui-font-color1);\n",
       "}\n",
       ".tuneStatus .systemInfo {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus td {\n",
       "  white-space: nowrap;\n",
       "}\n",
       ".tuneStatus .trialStatus {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       ".tuneStatus h3 {\n",
       "  font-weight: bold;\n",
       "}\n",
       ".tuneStatus .hDivider {\n",
       "  border-bottom-width: var(--jp-border-width);\n",
       "  border-bottom-color: var(--jp-border-color0);\n",
       "  border-bottom-style: solid;\n",
       "}\n",
       ".tuneStatus .vDivider {\n",
       "  border-left-width: var(--jp-border-width);\n",
       "  border-left-color: var(--jp-border-color0);\n",
       "  border-left-style: solid;\n",
       "  margin: 0.5em 1em 0.5em 1em;\n",
       "}\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "searcher = OptunaSearch(metric=[\"loss\", \"gain\"], mode=[\"min\", \"max\"])\n",
    "algo = ConcurrencyLimiter(searcher, max_concurrent=4)\n",
    "\n",
    "tuner = tune.Tuner(\n",
    "    multi_objective,\n",
    "    tune_config=tune.TuneConfig(\n",
    "        search_alg=algo,\n",
    "        num_samples=num_samples,\n",
    "    ),\n",
    "    param_space=search_space\n",
    ")\n",
    "results = tuner.fit();"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "df42b8b3",
   "metadata": {},
   "source": [
    "Now there are two hyperparameter sets for the two objectives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "183fef1a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best hyperparameters for loss found were:  {'steps': 100, 'width': 11.41302483988651, 'height': -31.950786209072476, 'activation': 'tanh'}\n",
      "Best hyperparameters for gain found were:  {'steps': 100, 'width': 19.532566002677832, 'height': 46.643925051045784, 'activation': 'relu'}\n"
     ]
    }
   ],
   "source": [
    "print(\"Best hyperparameters for loss found were: \", results.get_best_result(\"loss\", \"min\").config)\n",
    "print(\"Best hyperparameters for gain found were: \", results.get_best_result(\"gain\", \"max\").config)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "cdf4d49a",
   "metadata": {},
   "source": [
    "We can mix-and-match the use of initial hyperparameter evaluations, conditional search spaces via define-by-run functions, and multi-objective tasks. This is also true of scheduler usage, with the exception of multi-objective optimization-- schedulers typically rely on a single scalar score, rather than the two scores we use here: loss, gain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "a058fdb3",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "ray.shutdown()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ray",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  },
  "orphan": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
